<template>
    <LayoutHeader />
    <div class="container">
        <div class="main">
            <el-form ref="formRef" :model="form" :rules="registerRules">
                <h1 class="logo">Code OnlineJudge</h1>
                <el-form-item class="form-item" prop="account">
                    <el-input v-model="form.account" placeholder="请输入账号" @keyup.enter.native="register">
                        <template #prefix>
                            <i class="iconfont icon-yonghuming" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item class="form-item" prop="password">
                    <el-input v-model="form.password" type="password" autocomplete="off" show-password
                        placeholder="请输入密码" @keyup.enter.native="register">
                        <template #prefix>
                            <i class="iconfont icon-mima" />
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item class="form-item" prop="confirmPassword">
                    <el-input v-model="form.confirmPassword" type="password" autocomplete="off" show-password
                        placeholder="请确认密码" @keyup.enter.native="register">
                        <template #prefix>
                            <i class="iconfont icon-mima" />
                        </template>
                    </el-input>
                </el-form-item>

                <el-row>
                    <el-form-item style="width: 140px;" prop="identifyCode">
                        <el-input v-model="form.identifyCode" placeholder="请输入验证码" :validate-event="false"
                            @keyup.enter.native="register">
                            <template #prefix>
                                <i class="iconfont icon-yanzhengma" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <span @click="refreshCode" style="cursor: pointer; margin-left: 20px;">
                        <s-identify :identifyCode="identifyCode"></s-identify>
                    </span>
                </el-row>

                <el-row>
                    <el-col :span="6">
                        <el-checkbox v-model="autoLogin">自动登录</el-checkbox>
                    </el-col>
                    <el-col :span="11" :offset="7" style="line-height: 32px;">
                        <a @click="$router.push('/login')" class="login">已有账号？点击登录</a>
                    </el-col>
                </el-row>

                <el-row style="margin-top: 20px;">
                    <el-button type="primary" style="width: 100%;" @click="register" @keyup.enter.native="register">
                        注 册
                    </el-button>
                </el-row>
            </el-form>
        </div>
    </div>
    <LayoutFooter />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import router from '@/router/index.js'
import { ElMessage } from 'element-plus'
import { registerAPI } from '@/apis/user.js'
import SIdentify from '@/components/identify.vue'
import LayoutHeader from '../Layout/components/LayoutHeader.vue'
import LayoutFooter from '../Layout/components/LayoutFooter.vue'
import { sha256 } from 'js-sha256'

onMounted(() => {
    refreshCode()
})


const form = ref({
    account: "",
    password: "",
    confirmPassword: "",
    identifyCode: "",
})
const formRef = ref(null) // 表单对象实例

// 注册校验规则
const registerRules = {
    account: [
        { required: true, message: '账号不能为空', trigger: 'blur' },
        { min: 4, max: 10, message: '账号长度为4-10个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 128, message: '密码长度不能小于6', trigger: 'blur' }
    ],
    confirmPassword: [
        {
            validator: (rule, value, callback) => {
                if (value === "") {
                    callback(new Error('确认密码不能为空'))
                } else {
                    if (value === form.value.password) {
                        callback()
                    } else {
                        callback(new Error('两次输入密码不一致'))
                    }
                }
            },
            trigger: 'blur'
        }
    ],
    identifyCode: [
        { required: true, message: '验证码不能为空', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                console.log(value)
                // 自定义校验逻辑
                // 勾选就通过 不勾选就不通过
                if (value.toLowerCase() === identifyCode.value.toLocaleLowerCase()) {
                    callback()
                } else {
                    callback(new Error('验证码错误'), refreshCode(), form.value.identifyCode = "")
                }
            }
        }
    ]
}

// 是否自动登录
const autoLogin = ref(true)

const identifyCode = ref("")
const identifyCodeRule = '0123456789ABCDEFGHGKMNPQRSTUVWXYabcdefghijklmnopqrstuvwxyz'

function refreshCode() {
    identifyCode.value = ''
    makeCode(4)
}

function makeCode(l) {
    for (let i = 0; i < l; i++) {
        identifyCode.value += identifyCodeRule[Math.floor(Math.random() * (identifyCodeRule.length))]
    }
}


function register() {
    const { account } = form.value
    const password = sha256(form.value.password)
    // 调用表单实例验证方法
    formRef.value.validate(async (valid) => {
        // valid：所有表单都通过校验才为true
        if (valid) {
            try {
                const res = await registerAPI({ account, password })
                if (res.code !== 0) {
                    // 注册失败
                    ElMessage({ type: 'error', message: res.message })
                    form.value.password = ""
                    form.value.confirmPassword = ""
                    form.value.identifyCode = ""
                    refreshCode()
                } else {
                    // 注册成功
                    // 跳转登录页
                    ElMessage({ type: 'success', message: '注册成功' })
                    router.replace('/login')
                }
            } catch {
                ElMessage({ type: "error", message: "注册失败" })
            }
        }
    })

    // registerAPI(userInfo).then(({ data }))=> {
    //     if()
    // }
}

</script>

<style scoped lang="scss">
.container {
    height: 480px;

    .main {
        width: 400px;
        height: 440px;
        margin: 25px auto;
        padding: 0 60px;
        background-color: #ffffff;
        border-radius: 10px;
    }
}

.form-item {
    width: 280px;
}

.logo {
    width: 280px;
    height: 100px;
    margin: auto;
    line-height: 100px;
    text-align: center;
    color: #27ba9b;
}

.login {
    &:hover {
        color: $xtxColor;
        border-bottom: 1px solid $xtxColor;
        cursor: pointer;
    }
}
</style>